"use strict";
/**
 * 文件上传与下载服务类
 * 上传与下载路径可以在 config 配置中读取，根据操作系统不同，路径不同
 *
 * 还需要在 api.service.js 中配置，settings-->routes-->[{}]-->aliases   "POST /upload"
 *
 */

const _ 		= require("lodash");
const config = require("config");
const osSystem = require("os");
const appRoot = require('app-root-path');
const fs = require("fs");
const path = require("path");
const UUID = require('uuid');
const { NotFoundError } = require("moleculer-web");
const mkdir = require("mkdirp").sync;
const mime = require("mime-types");
let uploadDir = config["uploadDir"]["linux"];
if(osSystem.type() == "Windows_NT"){
	uploadDir = config["uploadDir"]["windows"];
}
mkdir(uploadDir);

module.exports = {
	name: "file",
	version:1,
	settings:{
		auth:"ignore",
	},
	actions: {
		get: {
			rest: {
				method:"GET",
				path:"/:fileName"
			},
			params:{
				fileName:{ type:"string", optional:false,description:"文件名称" },
			},
			handler(ctx) {
				const filePath = path.join(uploadDir, ctx.params.fileName);
				if (!fs.existsSync(filePath))
					throw new NotFoundError(`File not found ${ctx.params.fileName}`);
				const status = fs.statSync(filePath,{bigint:true});
				ctx.meta.$filename = ctx.params.fileName;
				ctx.meta.$contentLength = status.size;
				ctx.meta.$responseType = mime.lookup(filePath);

				// Return as stream
				return fs.createReadStream(filePath);
			}
		},

		save: {
			handler(ctx) {
				return new this.Promise((resolve, reject) => {
					const fileId = UUID.v1();
					const extension = mime.extension(mime.lookup(ctx.meta.filename));
					const filename = `${fileId}.${extension}`;
					const filePath = path.join(uploadDir,filename );
					const file = fs.createWriteStream(filePath);
					file.on("close", () => {
						// File written successfully
						this.logger.info(`Uploaded file stored in '${filePath}'`);
						resolve({ filename});
					});

					ctx.params.on("error", err => {
						this.logger.info("File error received", err.message);
						reject(err);

						// Destroy the local file
						file.destroy(err);
					});

					file.on("error", () => {
						// Remove the errored file.
						fs.unlinkSync(filePath);
					});
					ctx.params.pipe(file);
					this.logger.error(ctx.params["$params"]);
				});
			}
		},
	},
	methods: {

	}
};
